<?php

class ContactController extends Controller {
  
  public function init()
  {
      if (Yii::app()->user->isGuest){
          $this->redirect('/users/signin');
      }
    if (Yii::app()->request->isAjaxRequest) {
      $this->layout = false;
    }
    parent::init();
  }


  public function actionIndex()
  {
    $this->redirect('/contact/list');
  }

  public function actionList()
  {
    $contact_logs = ContactLogs::model()->findAll(array('order' => 'log_date desc'));
    $users = User::model()->sortById();
    $this->render('list', array('contact_logs' => $contact_logs, 'users' => $users));
  }

  public function actionCreate($id)
  {
    if ($id){
      $distributor = Distributors::model()->findByPk($id);
      $data = Yii::app()->request->getPost('data', false);
      if ($data){
        $arrPhoto =array();
        $log = new ContactLogs();
        $log->log_date = $data['log_date'];
        $log->contact_method = (int)$data['contact_method'];
        $log->contact_reason = (int)$data['contact_reason'];
        $log->user_id = Yii::app()->user->id;
        $log->distributor_id = $distributor->id;
        $log->contact_comment = $data['contact_comment'];
        if(isset($data['profile'])){
            $log->is_profile = $data['profile'];
        }else{
            $log->is_profile = 0;
        }
        if ($data['action'] === 'save'){
          $log->status = 1;
          $type = 'new';
        }else{
          $log->status = 0;
          $type = 'draft';
        }
        $log->save();
        
        /*check exist profile*/
        $photo_profile = json_decode($distributor->profile_pics);
        if(isset($photo_profile->all)) $arrPhoto['all']= $photo_profile->all;
        if(isset($photo_profile->outside)) $arrPhoto['outside']= $photo_profile->outside;
        if(isset($photo_profile->before)) $arrPhoto['before']= $photo_profile->before;
        if(isset($photo_profile->after)) $arrPhoto['after']= $photo_profile->after;
        if(isset($photo_profile->display)) $arrPhoto['display']= $photo_profile->display;
        if(isset($photo_profile->optional)) $arrPhoto['optional']= $photo_profile->optional;
        if(isset($photo_profile->staff)) $arrPhoto['staff']= $photo_profile->staff;
        
        
        if((isset($data['profile_all'])) && ($data['profile_all'] !='')){
            $arrPhoto['all'] = $log->id;
        }
        
        $photos = Yii::app()->request->getPost('photos', false);
        
        if ($photos){
            if(isset($data['profile'])&& ($data['profile'] !='')){
                if ($photos['outside'] != ''){
                   $outside =  $this->_photo_upload(1, $photos['outside'], $distributor->id, $data['log_date'], $log->id);
                   $arrPhoto['outside']=$outside;
                }else{
                    $arrPhoto['outside'] ='';
                }
                if ($photos['before'] != ''){
                    $before = $this->_photo_upload(2, $photos['before'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['before'] = $before;
                    }
                }else{
                    $arrPhoto['before']='';
                }
                if ($photos['after'] != ''){
                    $after= $this->_photo_upload(3, $photos['after'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['after'] = $after;
                    }
                }else{
                    $arrPhoto['after']='';
                }
                if ($photos['display'] != ''){
                    $display = $this->_photo_upload(4, $photos['display'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['display'] = $display;
                    }
                }else{
                    $arrPhoto['display']='';
                }
                
                if ($photos['optional'] != ''){
                    $optional = $this->_photo_upload(5, $photos['optional'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['optional'] = $optional;
                    }
                }else{
                    $arrPhoto['optional']='';
                }
                if ($photos['staff'] != ''){
                    $staff = $this->_photo_upload(6, $photos['staff'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['staff'] = $staff;
                    }
                }else{
                    $arrPhoto['staff']='';
                }
                
            }else{
                if ($photos['outside'] != ''){
                    $outside = $this->_photo_upload(1, $photos['outside'], $distributor->id, $data['log_date'], $log->id);
                }else{
                    $photos['outside'] = '';
                }
                if ($photos['before'] != ''){
                    $before = $this->_photo_upload(2, $photos['before'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['before'] = $before;
                    }
                }else{
                    $arrPhoto['before']='';
                }
                if ($photos['after'] != ''){
                    $after = $this->_photo_upload(3, $photos['after'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['after'] = $after;
                    }
                }else{
                    $arrPhoto['after']='';
                }
                if ($photos['display'] != ''){
                    $display = $this->_photo_upload(4, $photos['display'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['display'] = $display;
                    }
                }else{
                    $arrPhoto['display']='';
                }
                if ($photos['optional'] != ''){
                    $optional = $this->_photo_upload(5, $photos['optional'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['optional'] = $optional;
                    }
                }else{
                    $arrPhoto['optional']='';
                }
                if ($photos['staff'] != ''){
                    $staff = $this->_photo_upload(6, $photos['staff'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['staff'] = $staff;
                    }
                }else{
                    $arrPhoto['staff']='';
                }
            }
        }
        $distributor->profile_pics =  json_encode($arrPhoto);
        $distributor->update();
        $this->redirect('/distributors/view/'.$id );
      }else{
        $this->render('create', array('distributor' => $distributor));
      }
    }else{
      $this->redirect('/contact/list');
    }
  }

  public function actionEdit($id)
  {
    if ($id){
      $log = ContactLogs::model()->findByPk($id);
      if(!$log){
        $this->redirect('/contact/list');
      }
      $distributor = Distributors::model()->findByPk($log->distributor_id);
      $photo_profile = json_decode($distributor->profile_pics);
      $data = Yii::app()->request->getPost('data', false);
      $profile_all = 0;
      if((isset($photo_profile->all)) && ($photo_profile->all == $id)){
        $profile_all = 1;
      }
      if ($data){
        $arrPhoto =array();
        $log->log_date = $data['log_date'];
        $log->contact_method = (int)$data['contact_method'];
        $log->contact_reason = (int)$data['contact_reason'];
        $log->user_id = Yii::app()->user->id;
        $log->distributor_id = $distributor->id;
        $log->contact_comment = $data['contact_comment'];
        if ($data['action'] === 'save'){
          $log->status = 1;
          $type = 'new';
        }else{
          $log->status = 0;
          $type = 'draft';
        }
        if(isset($data['profile'])&& ($data['profile'] !='')){
            $log->is_profile = 1;
        }else{
            $log->is_profile = 0;
        }
        $log->update();
        /*check exist profile*/
        if(isset($photo_profile->all)) $arrPhoto['all']= $photo_profile->all;
        if(isset($photo_profile->outside)) $arrPhoto['outside']= $photo_profile->outside;
        if(isset($photo_profile->before)) $arrPhoto['before']= $photo_profile->before;
        if(isset($photo_profile->after)) $arrPhoto['after']= $photo_profile->after;
        if(isset($photo_profile->display)) $arrPhoto['display']= $photo_profile->display;
        if(isset($photo_profile->optional)) $arrPhoto['optional']= $photo_profile->optional;
        if(isset($photo_profile->staff)) $arrPhoto['staff']= $photo_profile->staff;
        
        
        if((isset($data['profile_all'])) && ($data['profile_all'] !='')){
            $arrPhoto['all'] = $log->id;
        }else{
            $profile_all = 0;
        }
        
        $photos = Yii::app()->request->getPost('photos', false);
        if ($photos){
            if(isset($data['profile'])&& ($data['profile'] !='')){
                if ($photos['outside'] != ''){
                    $outside = $this->_photo_update(1, $photos['outside'], $distributor->id, $data['log_date'], $log->id);
                    $arrPhoto['outside']=$outside;
                }else{
                    if((isset($data["tmp_outside"])) && ($data["tmp_outside"])){
                        $arrPhoto['outside'] = $data["tmp_outside"];
                    }else{
                        $arrPhoto['outside']='';
                    }
                }
                
                if ($photos['before'] != ''){
                    $before = $this->_photo_update(2, $photos['before'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['before'] = $before;
                    }
                }else{
                    if((isset($data["tmp_before"])) && ($data['tmp_before'] !='')){
                        if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                            $arrPhoto['before'] = $data['tmp_before'];
                        }else{
                            $arrPhoto['before']='';
                        }
                    }
                }
                
                if ($photos['after'] != ''){
                    $after = $this->_photo_update(3, $photos['after'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['after'] = $after;
                    }
                }else{
                    if((isset($data["tmp_after"])) && ($data['tmp_after'] !='')){
                        if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                            $arrPhoto['after'] = $data['tmp_after'];
                        }else{
                            $arrPhoto['after']='';
                        }
                    }
                }
                
                if ($photos['display'] != ''){
                    $display = $this->_photo_update(4, $photos['display'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['display'] = $display;
                    }
                }else{
                    if((isset($data["tmp_display"])) && ($data['tmp_display'] !='')){
                        if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                            $arrPhoto['display'] = $data['tmp_display'];
                        }else{
                            $arrPhoto['display']='';
                        }
                    }
                }
                
                if ($photos['optional'] != ''){
                    $optional = $this->_photo_update(5, $photos['optional'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['optional'] = $optional;
                    }
                }else{
                    if((isset($data["tmp_optional"])) && ($data['tmp_optional'] !='')){
                        if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                            $arrPhoto['optional'] = $data['tmp_optional'];
                        }else{
                            $arrPhoto['optional']='';
                        }
                    }
                }
                if ($photos['staff'] != ''){
                    $staff = $this->_photo_update(6, $photos['staff'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['staff'] = $staff;
                    }
                }else{
                    if((isset($data["tmp_staff"])) && ($data['tmp_staff'] !='')){
                        if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                            $arrPhoto['staff'] = $data['tmp_staff'];
                        }else{
                            $arrPhoto['staff']='';
                        }
                    }
                }
                
            }else{
                if ($photos['outside'] != ''){
                    $this->_photo_update(1, $photos['outside'], $distributor->id, $data['log_date'], $log->id);
                }else{
                    if((isset($data["tmp_outside"])) && ($data["tmp_outside"])){
                        $arrPhoto['outside'] = $data["tmp_outside"];
                    }else{
                        $arrPhoto['outside']='';
                    }
                }
                if ($photos['before'] != ''){
                    $before = $this->_photo_update(2, $photos['before'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['before'] = $before;
                    }
                }else{
                    if((isset($data["tmp_before"])) && ($data['tmp_before'] !='')){
                        if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                            $arrPhoto['before'] = $data['tmp_before'];
                        }else{
                            $arrPhoto['before']='';
                        }
                    }
                }
                
                if ($photos['after'] != ''){
                    $after = $this->_photo_update(3, $photos['after'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['after'] = $after;
                    }
                }else{
                    if((isset($data["tmp_after"])) && ($data['tmp_after'] !='')){
                        if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                            $arrPhoto['after'] = $data['tmp_after'];
                        }else{
                            $arrPhoto['after']='';
                        }
                    }
                }
                
                if ($photos['display'] != ''){
                    $display = $this->_photo_update(4, $photos['display'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['display'] = $display;
                    }
                }else{
                    if((isset($data["tmp_display"])) && ($data['tmp_display'] !='')){
                        if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                            $arrPhoto['display'] = $data['tmp_display'];
                        }else{
                            $arrPhoto['display']='';
                        }
                    }
                }
                
                if ($photos['optional'] != ''){
                    $optional = $this->_photo_update(5, $photos['optional'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['optional'] = $optional;
                    }
                }else{
                    if((isset($data["tmp_optional"])) && ($data['tmp_optional'] !='')){
                        if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                            $arrPhoto['optional'] = $data['tmp_optional'];
                        }else{
                            $arrPhoto['optional']='';
                        }
                    }
                }
                
                if ($photos['staff'] != ''){
                    $staff = $this->_photo_update(6, $photos['staff'], $distributor->id, $data['log_date'], $log->id);
                    if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                        $arrPhoto['staff'] = $staff;
                    }
                }else{
                    if((isset($data["tmp_staff"])) && ($data['tmp_staff'] !='')){
                        if((isset($data['profile_all'])) && ($data['profile_all'] == 1)){
                            $arrPhoto['staff'] = $data['tmp_staff'];
                        }else{
                            $arrPhoto['staff']='';
                        }
                    }
                }
            }
        }
        if(!isset($data['profile_all'])){
              $arrPhoto['before'] = '';
              $arrPhoto['after'] = '';
              $arrPhoto['display'] = '';
              $arrPhoto['optional'] = '';
              $arrPhoto['staff'] = '';
              $arrPhoto['all'] = '';
        }
        if(!isset($data['profile'])){
            $arrPhoto['outside'] = '';
        }
        $distributor->profile_pics =  json_encode($arrPhoto);
        $distributor->update();
        $this->redirect(array('view','id'=>$id));
        //$this->render('success', array('type' => $type));
      }else{
        $this->render('edit', array('distributor' => $distributor, 'contact_log' => $log, 'profile_all'=>$profile_all));
      }
    }else{
      $this->redirect('/contact/list');
    }
  }

  public function actionDelete($id)
  {
    $log = ContactLogs::model()->findByPk($id);
    if (Yii::app()->user->role == 'admin' && $log){
      if (Yii::app()->request->isPostRequest){
        $photo  = Photos::model()->findAllByAttributes(array('contact_log_id'=>$log->id));
        $distributor =  Distributors::model()->findByPk($log->distributor_id);
        if(isset($distributor)){
            $profile_pics = json_decode($distributor->profile_pics);
        }
        $arrPhoto =array();
        if(isset($profile_pics)){
            if((isset($profile_pics->all)) && ($profile_pics->all !='')){
                if($id == $profile_pics->all ){
                    $arrPhoto['before'] = '';
                    $arrPhoto['after'] = '';
                    $arrPhoto['display'] = '';
                    $arrPhoto['optional'] = '';
                    $arrPhoto['staff'] = '';
                    $arrPhoto['all'] = '';
                    $arrPhoto['outside'] = '';
                    $distributor->profile_pics =  json_encode($arrPhoto);
                    $distributor->update();
                }
            }
        }
        $log->delete();
        
        $this->render('delete', array('success' => true, 'contact'=>$log));
      }else{
        $this->render('delete', array());
      }
    }else{
      $this->redirect('/contact/list');
    }
  }

  public function actionView($id)
  {
    if ($id){
        $contact = ContactLogs::model()->findByPk($id);
        $distributor = Distributors::model()->findByPk($contact->distributor_id);
        $sql = "SELECT * FROM photos WHERE contact_log_id = ".$id;
        $photo = Photos::model()->findAllBySql($sql);
        $this->render('view', array('contact' => $contact, 'distributor' => $distributor, 'photo'=>$photo));
    }else{
        $this->redirect('/contact/list');
    }
  }

  public function actionUpload()
  {
    if(Yii::app()->request->isAjaxRequest){
        $uploadDir = '/public/photos/tmp/';
    //var_dump($_POST); die();

    // Set the allowed file extensions
    $fileTypes = array('jpg', 'jpeg', 'gif', 'png'); // Allowed file extensions

    //$verifyToken = md5('unique_salt' . $_POST['timestamp']);

    if (!empty($_FILES)) {
      $tempFile   = $_FILES['uploads']['tmp_name'][0];
      $uploadDir  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;

      // Validate the filetype
      $fileParts = pathinfo($_FILES['uploads']['name'][0]);
      if (in_array(strtolower($fileParts['extension']), $fileTypes)) {

        $uid = uniqid();
        $filename = $uid . '.' . $fileParts['extension'];
        $targetFile = $uploadDir . $filename;
        
        // Save the file
		if(move_uploaded_file($tempFile, $targetFile)){
			 // VARS FOR FILE NAMES
			$thumbnail = $uploadDir."medium_".$filename;
			$actual = $uploadDir."large_".$filename;

			// THUMBNAIL SIZE
			list($width, $height) = getimagesize($targetFile);
			$newwidth = "545"; 
			$newheight = "406";

			// VARS FOR CALL BACK
			$thumb = imagecreatetruecolor($newwidth, $newheight);
			$source = imagecreatefromjpeg($targetFile);

			// RESIZE WITH PROPORTION LIKE PHOTOSHOP HOLDING SHIFT
			imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

			// MAKE NEW FILES
			imagejpeg($thumb, $thumbnail, 100);

			// FILE RENAMES
			rename($targetFile, $actual);

			echo CJSON::encode(array('file' => '/public/photos/tmp/medium_'.$filename, 'filename' => "medium_".$filename));
		}
      } else {
        // The file type wasn't allowed
        echo 'Invalid file type.';
      }
    }
    }
    
  }

  private function _photo_upload($type, $filename, $did, $log_date, $clid)
  {
    $uploadDir = '/public/photos/';
    $tempFile  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir . 'tmp/' . $filename;
    $targetFile = $_SERVER['DOCUMENT_ROOT'] . $uploadDir . $filename;
    rename($tempFile, $targetFile);
    
    $photo = new Photos();
    $photo->distributor_id = $did;
    $photo->name = $filename;
    $photo->photo_type = $type;
    $photo->upload_date = date("Y-m-d H:i:s");
    $photo->show_photo = 1;
    $photo->visit_date = $log_date;
    $photo->user_id = Yii::app()->user->id;
    $photo->contact_log_id = $clid;
    $photo->save();
    return $photo->id;
  }
  
  private function _photo_update($type, $filename, $did, $log_date, $clid){
    
    $uploadDir = '/public/photos/';
    $tempFile  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir . 'tmp/' . $filename;
    $targetFile = $_SERVER['DOCUMENT_ROOT'] . $uploadDir . $filename;
    rename($tempFile, $targetFile);
    

    $photo = Photos::model()->findByAttributes(array('contact_log_id'=>$clid, 'distributor_id'=>$did, 'photo_type'=>$type ));
    
    if($photo){
        $photo->name = $filename;
        $photo->upload_date = date("Y-m-d H:i:s");
        $photo->show_photo = 1;
        $photo->visit_date = $log_date;
        $photo->user_id = Yii::app()->user->id;
        $photo->update();
        return $photo->id;
    }else{
        $photo = new Photos();
        $photo->distributor_id = $did;
        $photo->name = $filename;
        $photo->photo_type = $type;
        $photo->upload_date = date("Y-m-d H:i:s");
        $photo->show_photo = 1;
        $photo->visit_date = $log_date;
        $photo->user_id = Yii::app()->user->id;
        $photo->contact_log_id = $clid;
        $photo->save();
        return $photo->id;
    }
  }

}